package cn.lhx.blog.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.lhx.blog.util.TimeTookit2;

public class UploadServlet extends HttpServlet {

	private String uploadFileRealPath; // 上传文件的目录
	private String uploadPath; // 临时文件目录

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// 得到servlet配置中的文件存放的相对路径
		String updoadFilePath = this.getInitParameter("updoadFilePath");
		// 得到servlet配置中的文件存放的物理目录
		uploadFileRealPath = this.getServletContext().getRealPath(
				updoadFilePath);
		System.out.println("相对路径：" + updoadFilePath + ";物理路径："
				+ uploadFileRealPath);
		// 是否上传成功
		boolean state = false;
		// 用来引用上传成功的文件,以给客户端输出
		java.util.List<File> upokFiles = new java.util.ArrayList<File>();
		// 用来引用非文件属性
		java.util.Map<String, String> formFileds = new HashMap<String, String>();
		try {
			// 创建一个基于磁盘文件的工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setRepository(new File(uploadFileRealPath));
			factory.setSizeThreshold(10);
			// 创建一个文件处理器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置编码格式
//			req.setCharacterEncoding("utf-8");
			// 解析请求
			List items = upload.parseRequest(req);
			// 处理文件上传项
			Iterator iter = items.iterator();
			int itemIndex=0;
			while (iter.hasNext()) {
				
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					System.out.println(item);
					// 普通请求,可以接收请求中其它参数
					System.out.println("普通请求,可以接收请求中其它参数");
					String name = item.getFieldName()+"_"+itemIndex;
					String value = item.getString();
					formFileds.put(name, value);

				} else {
					// 文件上传请求
					// 获得上传文件名
					String originFileName = item.getName();
					System.out.println("orginFileName: " + originFileName);

					if (originFileName.trim().length() == 0)
						continue;
					File targtFile = this.createFileOnServer(originFileName);
					if (null != targtFile) {
						// 写入文件
						System.out.println("保存的路径为: "
								+ targtFile.getAbsolutePath());
						// 将文件写入服务器上的目录
						item.write(targtFile);
						upokFiles.add(targtFile);
						state = true;
						itemIndex++;
					}
				}
			
			}
		} catch (Exception ef) {
			ef.printStackTrace();
		}
		if (state) {
			req.setAttribute("formFileds", formFileds);
			req.setAttribute("upokFiles", upokFiles);
			req.getRequestDispatcher(
					"/admin/uploadAction.do?method=saveUploadInfo").forward(
					req, resp);
		}
		else {
			System.out.println("UploadFail!");
		}

	}

	/**
	 * 生成服务器端文件
	 */
	protected File createFileOnServer(String orginFileName) {
		System.out.println("ordddddddddd"+orginFileName);
		String fileName =orginFileName;
		// 截取文件名
			if(-1!=orginFileName.lastIndexOf("\\")){
				fileName = orginFileName.substring(orginFileName.lastIndexOf("\\"));
			}
		
		String directory = getDirectory();
		File targetFile = null;
		try {// 出错返回Null
			targetFile = getFile(directory + "\\" + fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return targetFile;

	}

	/**
	 * 生成保存的目录
	 * 
	 * @return
	 */
	private String getDirectory() {
		// 放入对应年、月的文件夹中
		Date date = new Date();
		File yearFile = new File(uploadFileRealPath + "\\"
				+ TimeTookit2.getYear(date));
		File monthFile = new File(yearFile.getAbsolutePath() + "\\"
				+ TimeTookit2.getMonth(date));
		// 年文件夹存在且是个目录
		if (yearFile.exists() && yearFile.isDirectory()) {
			// 月文件夹存在且是个目录
			if (monthFile.exists() && monthFile.isDirectory()) {
				;// 什么都不干
			} else {// 只创建月文件夹
				monthFile.mkdir();
			}
		} else {// 年文件夹不存在，则创建它和月文件夹
			yearFile.mkdir();
			monthFile.mkdir();
		}
		return monthFile.getAbsolutePath();
	}

	/**
	 *生成最终文件对象，采用了防止同名文件的策略： <br>
	 * 如果文件名相同，则根据文件名后面+系统时间tickets 的十六进制形式字符串
	 * 
	 * @param file
	 * @return
	 */
	private File getFile(String fileName) throws Exception {
		File file = new File(fileName);
		// 必须是文件
		if (file.isDirectory()) {
			throw new RuntimeException("Error! file is not a file!");
		}
		if (file.exists()) {// 有相同的文件存在
			String fileNameIngoreDix = fileName.substring(0, fileName
					.lastIndexOf("."));
			// 求后缀
			String dix = fileName.substring(fileName.lastIndexOf("."));

			long timeTickets = System.currentTimeMillis();
			String addStr = Long.toString(timeTickets, 16);
			StringBuilder sb = new StringBuilder();
			sb.append(fileNameIngoreDix + "_");
			sb.append(addStr);
			sb.append(dix);
			file = new File(sb.toString());
			// //保证时间不一致
			// Thread.sleep(10);
		}
		return file;
	}

}
